import Axios, { type AxiosInstance, type AxiosError, type AxiosResponse, type AxiosRequestConfig } from "axios";
import { ContentTypeEnum, ResultEnum } from "@/enums/requestEnum";
import NProgress from "../progress";
import { showFailToast, showDialog, showLoadingToast, closeToast } from "vant";
import "vant/es/toast/style";
import { gotoPath, getAssetsFile, gotoPathReplace } from "@/utils/common";
// import { createGtagPlugin } from "vue-gtag";
// const gtag = createGtagPlugin({
//   property: {
//     id: "G-2P661FN661"
//   }
// });
// gtag.page("YOUR_PAGE_PATH");
// 默认 axios 实例请求配置
const configDefault = {
  headers: {
    "Content-Type": ContentTypeEnum.FORM_URLENCODED
  },
  timeout: 0,
  baseURL: import.meta.env.VITE_BASE_API,
  data: {}
};

class Http {
  // 当前实例
  private static axiosInstance: AxiosInstance;
  // 请求配置
  private static axiosConfigDefault: AxiosRequestConfig;

  // 请求拦截
  private httpInterceptorsRequest(): void {
    Http.axiosInstance.interceptors.request.use(
      config => {
        // NProgress.start();
        // 发送请求前，可在此携带 token
        const token = localStorage.getItem("api_token");
        if (token) {
          config.headers["Authorization"] = `Bearer ${token}`;
        }
        return config;
      },
      (error: AxiosError) => {
        showFailToast(error.message);
        return Promise.reject(error);
      }
    );
  }

  // 响应拦截
  private httpInterceptorsResponse(): void {
    Http.axiosInstance.interceptors.response.use(
      (response: AxiosResponse) => {
        closeToast();
        // if (!localStorage.getItem("ageStatement")) {
        //   gotoPath("/ageStatement");
        //   return;
        // }
        // if (!localStorage.getItem("disclaimers")) {
        //   gotoPath("/disclaimers");
        //   return;
        // }
        // NProgress.done();
        // 与后端协定的返回字段
        const { code, msg, data } = response.data;
        // 判断请求是否成功
        console.log(code, msg, data);
        const isSuccess =  Reflect.has(response.data, "code");
        if (isSuccess) {
          console.log(code, msg, data);
          if (code === 0) {
            return response.data;
          } else if (code === 1) {
            return showDialog({
              title: "提示",
              message: msg,
              width: "300px",
              confirmButtonColor: "#3491FA",
              theme: "round-button"
            }).then(() => {
              response.data;
            });
          } else if (code === 2) {
            return showDialog({
              message: "登录失效啦~ 请重新登录账号吧！",
              width: "300px",
              confirmButtonColor: "#3491FA",
              theme: "round-button"
            }).then(() => {
              const currentUrl = window.location.href.split("#")[1];
              console.log(currentUrl);
              localStorage.setItem("jumpPage", currentUrl);
              // gotoPath("/login");
              gotoPathReplace("/login");
            });
          }
        } else {
          // 处理请求错误
          // showFailToast(message);
          return Promise.reject(response.data);
        }
      },
      (error: AxiosError) => {
        // NProgress.done();
        // 处理 HTTP 网络错误
        let message = "";
        // HTTP 状态码
        const status = error.response?.status;
        switch (status) {
          case 400:
            message = "请求错误";
            break;
          case 401:
            message = "未授权，请登录";
            showDialog({
              message: "登录失效啦~ 请重新登录账号吧！",
              width: "300px",
              confirmButtonColor: "#3491FA",
              theme: "round-button"
            }).then(() => {
              gotoPathReplace("/login");
            });
            break;
          case 403:
            message = "拒绝访问";
            break;
          case 404:
            message = `请求地址出错: ${error.response?.config?.url}`;
            break;
          case 408:
            message = "请求超时";
            break;
          case 500:
            message = "服务器内部错误";
            break;
          case 501:
            message = "服务未实现";
            break;
          case 502:
            message = "网关错误";
            break;
          case 503:
            message = "服务不可用";
            break;
          case 504:
            message = "网关超时";
            break;
          case 505:
            message = "HTTP版本不受支持";
            break;
          default:
            message = "网络连接故障";
        }
        if (status == 401) return;
        showFailToast(message);
        return Promise.reject(error);
      }
    );
  }

  constructor(config: AxiosRequestConfig) {
    Http.axiosConfigDefault = config;
    Http.axiosInstance = Axios.create(config);
    this.httpInterceptorsRequest();
    this.httpInterceptorsResponse();
  }

  // 通用请求函数
  public request<T>(paramConfig: AxiosRequestConfig): Promise<T> {
    showLoadingToast("loading...");
    const config = Object.assign(Http.axiosConfigDefault, paramConfig);
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          closeToast()
          resolve(response);
        })
        .catch(error => {
          closeToast()
          reject(error);
        });
    });
  }

  public get<T>(url: string): Promise<T> {
    showLoadingToast({ message: "loading...", forbidClick: true });
    const config = Object.assign(Http.axiosConfigDefault, {
      url: url,
      method: "get"
    });
    // console.log(config, url);
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  public post<T>(url: string, data = {}): Promise<T> {
    showLoadingToast({ message: "", forbidClick: true });
    const config = Object.assign(Http.axiosConfigDefault, {
      url: url,
      data: data,
      method: "post",
      headers: {
        'Content-Type': 'application/json;charset=UTF-8'
      },
    });
    // console.log(config, url);
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }

  public put<T>(url: string, data = {}): Promise<T> {
    showLoadingToast({ message: "", forbidClick: true });

    const config = Object.assign(Http.axiosConfigDefault, {
      url: url,
      data: data,
      method: "put"
    });
    // console.log(config, url);
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
  public delete<T>(url: string, data = {}): Promise<T> {
    showLoadingToast("");
    const config = Object.assign(Http.axiosConfigDefault, {
      url: url,
      data: data,
      method: "delete"
    });
    // console.log(config, url);
    return new Promise((resolve, reject) => {
      Http.axiosInstance
        .request(config)
        .then((response: any) => {
          resolve(response);
        })
        .catch(error => {
          reject(error);
        });
    });
  }
}

export const http = new Http(configDefault);
